package com.device.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.device.dataobject.ro.ResultTemplate;
import com.device.dataobject.ro.TemplateData;
import com.device.dataobject.ro.WxMsgVo;
import com.device.dataobject.vo.ResultVO;
import com.device.util.HttpUtil;
import com.device.util.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class SendTemplateServiceImpl {
    private final RestTemplate restTemplate;

    @Autowired
    public SendTemplateServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 订阅消息发送 调用微信请求
     */
    public ResultVO send(WxMsgVo wxMsgVo) {
        String tepUrl;
        tepUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        ResponseEntity<String> str = restTemplate.postForEntity(tepUrl, wxMsgVo, String.class);
        ResultTemplate resultTemplate= JSONObject.parseObject(str.getBody(), ResultTemplate.class);
        String resultStr = "null";
        if (resultTemplate != null) {
            resultStr = resultTemplate.getList().getErrorCode();
        }
        return ResultVOUtil.returnSuccess(resultStr);
    }


    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + "小程序的appid"
                + "&secret="
                + "小程序的Secret";
        String result = HttpUtil.sendGet(url);
        JSONObject object = JSON.parseObject(result);
        return object.getString("access_token");
    }

    public static void main(String[] args) {
        WxMsgVo wxMsgVo = new WxMsgVo();
        wxMsgVo.setTemplate_id("TemplateId");
        wxMsgVo.setTouser("OpenId");
        Map<String, TemplateData> data = new HashMap<>();
        data.put("name1", new TemplateData("活动名称"));//活动名称
        data.put("thing4", new TemplateData("用户昵称"));//用户昵称
        data.put("time3", new TemplateData("2020-01-01 11:11:11"));//完成时间
        data.put("thing5", new TemplateData("温馨提示"));//温馨提示
        wxMsgVo.setData(data);


    }
}


